<template>
  <div class="update-password">
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      
      <div class="password-content">
        <el-form 
          :model="passwordForm" 
          :rules="passwordRules" 
          ref="passwordFormRef" 
          label-width="120px"
        >
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input 
              v-model="passwordForm.oldPassword" 
              type="password" 
              show-password
              placeholder="请输入当前密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              show-password
              placeholder="请输入新密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              show-password
              placeholder="请再次输入新密码"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="submitForm" 
              :loading="loading"
            >
              确认修改
            </el-button>
            <el-button 
              @click="resetForm" 
              :disabled="loading"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <div class="password-tips">
      <el-alert title="密码安全提示" type="info" :closable="false">
        <ul>
          <li>密码长度至少8个字符</li>
          <li>建议包含大小写字母、数字和特殊符号</li>
          <li>不要使用生日、电话号码等容易被猜到的密码</li>
          <li>定期更换密码可以提高账户安全性</li>
        </ul>
      </el-alert>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import router from '@/router/index.js'

const passwordFormRef = ref(null)
const loading = ref(false)

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 8) {
    callback(new Error('密码长度不能少于8位'))
  } else {
    if (passwordForm.confirmPassword !== '') {
      passwordFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const passwordRules = reactive({
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ]
})

const submitForm = async () => {
  try {
    loading.value = true
    await passwordFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          const response = await request.post('/api/user/change-password', {
            oldPassword: passwordForm.oldPassword,
            newPassword: passwordForm.newPassword
          })
          ElMessage.success(response.data.message || '密码修改成功')
          
          // 清除本地存储并跳转到登录页
          localStorage.removeItem('token')
          localStorage.removeItem('code_user')
          ElMessage.info('请重新登录')
          await router.push('/login')
        } catch (error) {
          const errorMessage = error.response?.data?.message || '密码修改失败'
          if (errorMessage.includes('old password')) {
            ElMessage.error('当前密码错误')
          } else {
            ElMessage.error(errorMessage)
          }
          console.error('Password change error:', error)
        }
      }
    })
  } catch (error) {
    ElMessage.error('表单验证失败')
    console.error('Form validation error:', error)
  } finally {
    loading.value = false
  }
}

const resetForm = () => {
  passwordFormRef.value.resetFields()
}
</script>

<style scoped>
.update-password {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.password-content {
  max-width: 600px;
}

.password-tips {
  margin-top: 30px;
  max-width: 600px;
}

.password-tips ul {
  margin: 10px 0 0 20px;
  padding: 0;
  line-height: 1.8;
}
</style>